<template>
    <div class="pageBox">
        <div class="top">
            <a-button type="primary" icon="plus" @click="add()" v-if="listButton.addition">新建</a-button>
        </div>
        <div class="table">
            <a-table  :pagination= show :dataSource="dataSource" :columns="columns" >
                <template slot="operation" slot-scope="text, record">
                    <a-button @click="change(record.id,record.name)"  type="primary" ghost v-if="listButton.editor">{{listButton.editor}}</a-button>
                    <a-button @click="remove(record.id)" type="danger" ghost v-if="listButton.cancel">{{listButton.cancel}}</a-button>
                </template>
            </a-table>
        </div>
        <div class="paging">
            <div class="total">共 {{total}} 条记录 第 {{par.pageSize}} / {{allPage}} 页</div>
            <a-pagination
                v-show="page"
                showQuickJumper
                showSizeChanger
                :defaultCurrent="1"
                :defaultPageSize="par.limit"
                :total = total
                @change="onChange"
            />
        </div>
        <!-- 模态框 -->
        <a-modal
            :title="title"
            width="1200px"
            v-model="visible"
            @ok="onOk()"
            @cancel="onCancel()"
            okText="确认"
            cancelText="取消"
            >
            <div class="item">
                <span>角色名称 : </span> <a-input :disabled="title=='修改角色'?disabled:noDisabled" style="width:240px;" v-model="addRole.name" placeholder="请输入"/>
            </div>
            <div class="item checkbox">
                <span>权限 : </span>
                <ul >
                    <li >
                         <a-tree
                            checkable
                            @check="onCheck"
                            v-model="checkedKeys"
                            :treeNodes="checkList"
                            @expand="onExpand"
                            :expandedKeys="expandedKeys"
                        />

                    </li>
                </ul>
            </div>
        </a-modal>
    </div>
</template>

<script>
import qs from "qs";
export default {
  data() {
    return {
      // data,
      disabled: true,
      noDisabled: false,
      show: false,
      page: true,
      total: null,
      visible: false,
      checkedList: [],
      title: "",
      par: {
        limit: 10,
        pageSize: 1
      },
      allPage: "",
      dataSource: [
        {
          name: "超级管理员",
          id: "广告管理"
        }
      ], //列表数据
      columns: [
        {
          title: "角色",
          dataIndex: "name"
        },
        {
          title: "操作",
          dataIndex: "operation",
          scopedSlots: {
            customRender: "operation"
          }
        }
      ],
      checkList: [],
      addRole: {
        p_ids: [],
        name: ""
      },
      checkedKeys: [],
      expandedKeys: [],
      listButton:{
        addition:"",//新建
        editor:"",//编辑
        cancel:""//删除
      }//按钮数据
    };
  },
  created() {
    let titleName=sessionStorage.getItem("stairH1");
    this.$ajax.get("/kmd-field-web/admin/queryBtn",{params:{"title":titleName.trim()}}).then(res=>{
      for(var i=0;i<res.data.list.length;i++){
        if(res.data.list[i].title=="新建"){
          this.listButton.addition=res.data.list[i].title
        }
        if(res.data.list[i].title=="编辑"){
          this.listButton.editor=res.data.list[i].title
        }
        if(res.data.list[i].title=="删除"){
          this.listButton.cancel=res.data.list[i].title
        }
      }
    })
    this.getData();
    this.allPermissions();
  },
  methods: {
    onCheck(checkedKeys, e) {
      this.addRole.p_ids = [];
      for (let i of e.checkedNodes.keys()) {
        let val = e.checkedNodes[i].data.props.id;
        this.addRole.p_ids.push(val);
      }
      let parents = e.halfCheckedKeys;
      for (let p = 0; p < parents.length; p++) {
        for (let f = 0; f < this.checkList.length; f++) {
          if (this.checkList[f].key == parents[p]) {
            let id = this.checkList[f].id;
            this.addRole.p_ids.push(id);
          }
          for(let s=0;s<this.checkList[f].children.length;s++){
            if (this.checkList[f].children[s].key == parents[p]) {
              let id = this.checkList[f].children[s].id;
              this.addRole.p_ids.push(id);
            }
          }
        }
      }
    },
    getData() {
      //获取数据列表
      this.$ajax
        .get("/kmd-field-web/role/rolePage", {
          params: this.par
        })
        .then(res => {
          this.dataSource = res.data.records;
          this.total = res.data.total;
          this.allPage = Math.ceil(this.total / this.par.limit);
        });
    },
    allPermissions() {
      //查询全部权限
      this.$ajax.get("/kmd-field-web/role/queryPermissions").then(res => {
        this.checkList = res.data.list;
        for (let i = 0; i < this.checkList.length; i++) {
          var val = this.checkList[i].items;
          this.checkList[i]["children"] = val;
          this.checkList[i]["key"] = `${i}`;
          for (let index = 0; index < this.checkList[i].items.length; index++) {
            let val1 = this.checkList[i].items[index].items;
            this.checkList[i].items[index]["children"] = val1;
            this.checkList[i].items[index]["key"] = `${i}-${index}`;
            for (
              let s = 0;
              s < this.checkList[i].items[index].items.length;
              s++
            ) {
              this.checkList[i].items[index].items[s][
                "key"
              ] = `${i}-${index}-${s}`;
            }
          }
        }
      });
    },
    onChange(pageNumber, limit) {
      // 分页跳转
      this.par.pageSize = pageNumber;
      this.par.limit = limit;
      this.getData();
    },
    add() {
      //添加角色
      this.title = "添加角色";
      this.visible = true;
    },
    onOk() {
      //模态框确认按钮事件
      if (this.title == "添加角色") {
        //添加角色
        if (this.addRole.name == "") {
          this.$message.warning("角色名称不能为空!");
          return;
        }
        if (this.addRole.checkedArr == "") {
          this.$message.warning("权限不能为空!");
          return;
        }
        this.$ajax
          .post("/kmd-field-web/role/insertRole", this.addRole)
          .then(res => {
            if (res.data.statusCode == 200) {
              this.$message.success("添加成功!");
              this.getData();
            } else {
              this.$message.error("添加失败,请稍后重试!");
            }
          })
          .catch(err => {
            this.$message.error("添加失败,服务器繁忙,请稍后重试!");
          });
      } else {
        this.$ajax
          .post("/kmd-field-web/role/modifyRolePermission", {
            p_ids: this.addRole.p_ids,
            role_id: this.addRole.role_id
          })
          .then(res => {
            if (res.data.statusCode == 200) {
              this.$message.success("修改成功!");

              this.getData();
            } else {
              this.$message.error("修改成功,请稍后重试!");
            }
          })
          .catch(err => {
            this.$message.error("修改失败,服务器繁忙,请稍后重试!");
          });
      }
      this.visible = false;
    },
    onCancel() {
      //模态框取消事件
      this.addRole.p_ids = [];
      this.addRole.name = "";
      this.checkedKeys = [];
      this.expandedKeys = [];
    },
    change(id, name) {
      //修改
      this.visible = true;
      this.title = "修改角色";
      this.addRole.name = name;
      this.addRole.role_id = id;
      this.$ajax
        .get("/kmd-field-web/role/rolePermissionPage", {
          params: {
            id: id
          }
        })
        .then(res => {
          this.checkList = res.data.list;
          for (let i = 0; i < this.checkList.length; i++) {
            var val = this.checkList[i].items;
            this.checkList[i]["children"] = val;
            this.checkList[i]["key"] = `${i}`;
            if (this.checkList[i].is_select == 2) {
              this.expandedKeys.push(this.checkList[i]["key"]);
              this.addRole.p_ids.push(this.checkList[i].id);
            }
            for (
              let index = 0;
              index < this.checkList[i].items.length;
              index++
            ) {
              let val1 = this.checkList[i].items[index].items;
              this.checkList[i].items[index]["children"] = val1;
              this.checkList[i].items[index]["key"] = `${i}-${index}`;
              if (this.checkList[i].items[index].is_select == 2) {
                this.expandedKeys.push(this.checkList[i].items[index]["key"]);
                this.addRole.p_ids.push(this.checkList[i].items[index].id);
              }
              for (let s = 0;s < this.checkList[i].items[index].items.length;s++) {
                this.checkList[i].items[index].items[s][
                  "key"
                ] = `${i}-${index}-${s}`;
                if (this.checkList[i].items[index].items[s].is_select == 2) {
                  this.checkedKeys.push(
                    this.checkList[i].items[index].items[s]["key"]
                  );
                  this.expandedKeys.push(
                    this.checkList[i].items[index].items[s]["key"]
                  );
                  this.addRole.p_ids.push(
                    this.checkList[i].items[index].items[s].id
                  );
                }
              }
            }
          }
        });
    },
    remove(id) {
      //删除角色
      let that = this;
      this.$confirm({
        title: "警告",
        content: "您确定要删除这个角色?",
        onOk() {
          that.$ajax
            .get("/kmd-field-web/role/deleteRole", {
              params: {
                id: id
              }
            })
            .then(res => {
              if (res.data.statusCode == 200) {
                that.$message.success("删除成功!");
                that.getData();
              } else {
                that.$message.error("删除失败!");
              }
            })
            .catch(err => {
              that.$message.error("删除失败,服务器繁忙,请稍后重试!");
            });
        }
      });
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
    }
  }
};
</script>

<style scoped lang="less">
.item {
  display: flex;
  align-items: center;
  span {
    width: 80px;
    text-align: right;
    padding-right: 10px;
  }
}
.checkbox {
  align-items: flex-start;
  padding: 20px 0;
  span {
    width: 80px;
    line-height: 40px;
  }
  ul {
    display: flex;
    li {
      flex: 1;
      .select {
        &:first-of-type {
          margin-top: 0;
        }
      }
    }
  }
}
</style>
